<template>
	<el-card shadow="never">
		<el-form
            :inline="true"
            :model="state.queryForm">
			<el-form-item>
				<el-input
                    v-model="state.queryForm.username"
                    placeholder="用户名">
                </el-input>
			</el-form-item>
			<el-form-item>
				<el-input
                    v-model="state.queryForm.mobile"
                    placeholder="手机号">
                </el-input>
			</el-form-item>
			<el-form-item>
				<el-select
                    v-model="state.queryForm.gender"
                    placeholder="性别"
                    style="width: 80px;"
                    clearable>
                    <el-option label="男" value="0" />
                    <el-option label="女" value="1" />
                </el-select>
			</el-form-item>
			<el-form-item>
				<el-button @click="onSearch()">查询</el-button>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="addBatch()">加入</el-button>
			</el-form-item>
			<el-form-item>
				<el-button type="danger" @click="removeBatch()">取消</el-button>
			</el-form-item>
		</el-form>
		<el-table
			ref="tableRef"
			v-loading="state.loading"
			:data="state.dataList"
			style="width: 100%"
			@selection-change="selectUserId"
			border>
			<el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
			<el-table-column prop="username" label="用户名" header-align="center" align="center"></el-table-column>
			<el-table-column prop="mobile" label="手机号" header-align="center" align="center"></el-table-column>
			<el-table-column prop="realName" label="姓名" header-align="center" align="center"></el-table-column>
			<el-table-column
                prop="gender"
                label="性别"
                header-align="center"
                align="center">
                <template #default="scope">
                    {{ scope.row.gender === 0 ? '男' : '女' }}
                </template>
            </el-table-column>
			<el-table-column label="操作" fixed="right" header-align="center" align="center" width="150">
				<template #default="scope">
					<el-button type="primary" link @click="addBatch(scope.row.id)">加入</el-button>
					<el-button type="primary" link @click="removeBatch(scope.row.id)">取消</el-button>
				</template>
			</el-table-column>
		</el-table>

        <div style="margin-top: 20px">
            <el-pagination
                layout="prev, pager, next"
                v-model:current-page="pagination.page"
                :page-size="pagination.limit"
                :total="pagination.total"
                @current-change="onPageChange"
                background>
            </el-pagination>
        </div>
	</el-card>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { userStore } from '@/store/user'
import { roleStore } from '@/store/role'
import { ElMessage, ElMessageBox } from 'element-plus'
const props = defineProps({
    roleId: {
        type: Number,
        required: true
    }
})
const useUserStore = userStore()
const useRoleStore = roleStore()

// 获取当前角色下的用户列表
const selectedIds = ref([]) // 存储选中ID
const tableRef = ref() // 添加表格引用
const getUserList = async () => {
    try {
        const { list } = await useRoleStore.getRoleUserPage({ roleId: props.roleId })
        
        // 提取已分配用户ID数组
        selectedIds.value = list.map(user => user.id);
        
        // 使用表格实例设置选中状态
        nextTick(() => {
            state.dataList.forEach(user => {
                if (selectedIds.value.includes(user.id)) {
                    tableRef.value.toggleRowSelection(user, true)
                }
            });
        });
    } catch (error) {
        ElMessage.error('获取用户列表失败')
    }
}

const state = reactive({
    queryForm: {
        username: '',
        mobile: '',
        gender: ''
    },
    loading: false,
    dataList: [], // 表格数据列表
})
state.dataList = computed(() => useUserStore.userList)
const pagination = computed(() => useUserStore.pagination)
// const { queryForm, loading, dataList, } = state;

onMounted(() => {
    onSearch(); // 页面加载时自动查询
})

const onSearch = async () => {
    state.loading = true; // 显示加载中状态
    try {
        await useUserStore.getUserList(state.queryForm);
        await getUserList();
    } catch (error) {
        console.error('获取用户列表失败:', error);
    } finally {
        state.loading = false; // 隐藏加载中状态
        // console.log(state.dataList);
    }
}

const onPageChange = (page) => {
    pagination.page = page; // 更新当前页码
    onSearch(); // 重新查询数据
}

// 勾选方法
const selectUserId = (selection) => {
    selectedIds.value = selection.map(user => user.id); // 同步更新selectedIds
    state.dataList.forEach(user => {
        user.checked = selection.includes(user); // 更新checked状态
    });
}

const addBatch = async (key) => {
    const ids = key ? [key] : [...selectedIds.value]
    if (ids.length === 0) {
        ElMessage.error('请选择要加入的用户'); // 提示用户选择用户
        return;
    }

    try {
        const confirm = await ElMessageBox.confirm('确定进行成员添加操作?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        
        if (confirm === 'confirm') {
            console.log('要添加的用户ID数组:', ids)
            console.log(`${props.roleId}-加入的ID: ${ids}`)
            await useRoleStore.addRoleUser(props.roleId, ids)
            ElMessage.success('角色成员添加成功！')
            await onSearch() // 刷新列表 { roleId: props.roleId }
        }
    } catch (error) {
        if(error !== 'cancel') { // 不是用户取消的情况
            ElMessage.error(error.message || '角色成员添加失败')
        }
    }
}

const removeBatch = async () => {
    const selectedUsers = state.dataList.filter(user => user.checked); // 获取选中的用户
    if (selectedUsers.length === 0) {
        ElMessage.error('请选择要取消的用户'); // 提示用户选择用户
        return;
    }
    console.log(selectedUsers);
}
</script>